<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item label="资料名称" prop="fileNameView">
            <el-input v-model="state.queryForm.fileNameView" clearable placeholder="请输入资料名称" />
          </el-form-item>
          <el-form-item label="提出异议人员" prop="personName">
            <el-input v-model="state.queryForm.personName" clearable placeholder="请输入提出异议人员" />
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="getDataList">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-table :data="state.dataList" v-loading="state.loading" border :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangHandle"
        @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="dataName" label="资料名称" show-overflow-tooltip />
        <el-table-column prop="fileNameAll" label="所属资料" show-overflow-tooltip />
        <el-table-column prop="reason" label="提出异议原因" show-overflow-tooltip />
        <el-table-column prop="personName" label="提出异议人员" show-overflow-tooltip />
        <el-table-column prop="createTime" label="时间" show-overflow-tooltip />
        <el-table-column label="操作" width="300">
          <!--          <template #default="scope">-->
          <!--&lt;!&ndash;        <el-button icon="edit-pen" text type="primary" v-auth="'train_kszlQuery_edit'" @click="preview(scope.row)">预览</el-button>&ndash;&gt;-->
          <!--            <el-button icon="edit-pen" text type="primary" v-auth="'train_kszlQuery_edit'"> <a :href="scope.row.fileAddress" target="_blank">预览</a></el-button>-->
          <!--            <el-button icon="delete" text type="primary" v-auth="'train_kszlQuery_del'" @click="handleDelete([scope.row.id])">删除</el-button>-->
          <!--          </template>-->
          <template #default="scope">
            <div class="downSty">
              <el-button type="primary" @click="preview(scope.row)">预览
                <!--                        <el-link :href="scope.row.fileAddress"  :underline="false" target="_blank" style="color: #fff">预览</el-link>-->
              </el-button>
              <el-button type="primary" @click="preview1(scope.row)">编辑
                <!--                        <el-link :href="scope.row.fileAddress"  :underline="false" target="_blank" style="color: #fff">编辑</el-link>-->
              </el-button>
              <el-button icon="delete" text type="primary" v-auth="'train_kszlQuery_del'"
                @click="handleDelete([scope.row.id])">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    </div>


  </div>
</template>

<script setup lang="ts" name="systemKszlQuery">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs } from "/@/api/train/kszlQuery";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';
import { office, officeType, officeView } from "/@/api/train/kszlFile";
import { ref } from "vue";
import { useUserInfo } from "/@/stores/userInfo";
import { ElMessage } from "element-plus";

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典
const random = ref()
const type = ref()
// 定义变量内容
const formDialogRef = ref()
// 搜索变量
const queryRef = ref()
const username = ref()
const fileType = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
const officeUrl = ref()
const officeUrl1 = ref()
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
})

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)


// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}
onMounted(() => {
  username.value = useUserInfo().userInfos.user.username
  // random.value= Math.floor(Math.random() * 100) + 1;
  // fetchList().then((res)=>{
  //     console.log(res,'res')
  // })
  office().then((res) => {
    officeUrl.value = res.data
    // console.log('res',res.data,officeUrl.value)
  })
  officeView().then((res) => {
    officeUrl1.value = res.data
    // console.log('res',res.data,officeUrl.value)
  })
  officeType().then((res) => {
    fileType.value = res.data
    // console.log(fileType.value)
  })
})
//预览
const preview = (row: any) => {
  type.value = row.dataType
  // let baseURL = import.meta.env.VITE_API_URL;
  // window.open(baseURL+ row.fileAddress)
  let originalUrl = `${officeUrl.value}/downloadFilec?id=${row.onlyOfficeId}`;
  let previewUrl = originalUrl + `&fullfilename=${row.dataFileId}${type.value}`
  console.log('previewUrl', previewUrl)
  //转换为 Base64 编码
  let base64EncodedUrl = btoa(previewUrl);
  //使用 encodeURIComponent 编码
  let encodedUrl = encodeURIComponent(base64EncodedUrl);
  let allUrl = officeUrl1.value + encodedUrl
  console.log(allUrl, "jhsjhd")
  window.open(allUrl);
}
const isFileTypeAllowed = (type: string, allowedTypes: string) => {
  // 将allowedTypes字符串按逗号分割成数组，并去除空格
  const allowedExtensions = allowedTypes.split(',').map(ext => ext.trim());
  // 检查type是否在allowedExtensions数组中
  return allowedExtensions.includes(type);
}
const preview1 = (row: any) => {
  const url = `${officeUrl.value}/edit?fileId=${row.onlyOfficeId}&userName=${username.value}&mode=edit`;
  // console.log(row,'row')
  let type = row.dataType.replace('.', '')

  if (isFileTypeAllowed(type, fileType.value)) {
    window.open(url);
  } else {
    ElMessage({
      message: '该类型资料不能进行编辑',
      type: 'warning',
    })
  }
}
// 导出excel
const exportExcel = () => {
  downBlobFile('/train/kszlQuery/export', Object.assign(state.queryForm, { ids: selectObjs }), 'kszlQuery.xlsx')
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }
  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
</script>